//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.huashi.otg.sdk;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class HsUsbHepler {
    public HsOTGSDK sdk;
    Context activity;

    public HsUsbHepler(Context activity) throws Exception {
        this.sdk = new HsOTGSDK(activity);
        this.activity = activity;
    }

    public int FindCard(long sendTime, long recvTime) {
        byte[] send = Hs_Cmd.cmd_find;
        byte[] recv = new byte[4096];
        int ret = send.length;
        this.sdk.usbSendRecv(send, recv, sendTime, recvTime, ret);
        return -97 == recv[9] ? 1 : 0;
    }

    public int SelectCard(long sendTime, long recvTime) {
        byte[] send = Hs_Cmd.cmd_selt;
        byte[] recv = new byte[4096];
        int ret = send.length;
        this.sdk.usbSendRecv(send, recv, sendTime, recvTime, ret);
        return -112 == recv[9] ? 1 : 0;
    }

    public int ReadCard(byte[] recv, long sendTime, long recvTime) {
        byte[] send = Hs_Cmd.cmd_read_ftp;
        int ret = send.length;
        this.sdk.usbSendRecv(send, recv, sendTime, recvTime, ret);
        return -112 == recv[9] ? 1 : 0;
    }

    public String getSAMID() {
        byte[] send = Hs_Cmd.cmd_SAM;
        byte[] recv = new byte[4096];
        int ret = send.length;
        this.sdk.usbSendRecv(send, recv, 5000L, 1000L, ret);
        return this.AnalyzeSAM(recv);
    }

    public byte[] getSAMIDByte() {
        byte[] send = Hs_Cmd.cmd_SAM;
        byte[] recv = new byte[4096];
        int ret = send.length;
        this.sdk.usbSendRecv(send, recv, 5000L, 1000L, ret);
        byte[] SAM = new byte[16];
        if (recv[6] == 20 && recv[9] == 144) {
            System.arraycopy(recv, 10, SAM, 0, SAM.length);
            return SAM;
        } else {
            return null;
        }
    }

    private String AnalyzeSAM(byte[] sambuffer) {
        if (sambuffer[9] != -112) {
            Toast.makeText(this.activity, "设备SAM号读取错误！", 0).show();
            return "";
        } else {
            byte[] samdate = new byte[4];
            System.arraycopy(sambuffer, 14, samdate, 0, 4);
            long ret = Long.valueOf(getLong(samdate));
            Log.e("AAAAAAA", String.valueOf(ret));
            byte[] samtenid = new byte[4];
            System.arraycopy(sambuffer, 18, samtenid, 0, 4);
            byte[] samstr = new byte[4];
            System.arraycopy(sambuffer, 22, samstr, 0, 4);
            String samid = String.format("%02d.%02d-%010d-%010d-%010d", sambuffer[10], sambuffer[12], getLong(samdate), getLong(samtenid), getLong(samstr));
            return samid;
        }
    }

    private static long getLong(byte[] buf) {
        long i = 0L;
        long tmp = 0L;

        for(int j = 0; j < buf.length; ++j) {
            tmp = (long)((buf[j] & 255) << j * 8);
            i |= tmp;
        }

        return i;
    }
}
